#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>

int main()
{
        pid_t id = fork();
        if(id == 0)
        {
                //child
                int cnt = 5;
                while(cnt)
                {
                        printf("Child is running, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
                        sleep(1);
                        cnt--;
                }
                printf("子进程准备退出, 马上变僵尸进程\n");
                exit(2);
        }
        //father
        int status = 0;
        while(1)
        {
                pid_t rid = waitpid(id, &status, WNOHANG);
                if(rid > 0)
                {
                        printf("wait success, rid: %d, status: %d, exit code: %d\n", rid, status, WEXITSTATUS(status));
                        break;
                }
                else if(rid == 0)
                {
                        printf("father say: child is running, do other things\n");
                }
                else 
                {
                        perror("waitpid");
                        break;

                }
                sleep(1);
        }
        //pid_t rid = waitpid(id, &status, 0);
        //if(rid > 0)
        //{
        //        //printf("wait success, rid: %d, status: %d, exit signo: %d, exit code: %d\n", rid, status, status&0x7F, (status>>8)&0xFF);//阻塞状态
       
        //        if(WIFEXITED(status))
        //        {
        //                printf("wait success, rid: %d, status: %d, exit code: %d\n", rid, status, WEXITSTATUS(status));
        //        }
        //        else{
        //                printf("child process error!\n");
        //        }
        //}
        //printf("父进程回收僵尸进程成功\n");
        //sleep(3);
        return 0;
}
